
#include <stdio.h>
#include "convex.h"

// 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
// Returns a positive value, if OAB makes a counter-clockwise turn,
// negative for clockwise turn, and zero if the points are collinear.
coord2_t cross(const point_t O, const point_t A, const point_t B)
{
        return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
}

void convex_hull(int N, point_t *P, point_t *H)
{
	int i = 0;
	int k = 0;
	int t = 0;

	// Build lower hull
    for (i = 0; i < N; i++) 
	{
        while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0)
		{
			k--;
		}
		H[k++] = P[i];
    }

    // Build upper hull
    for (i = N-2, t = k+1; i >= 0; i--) 
	{
        while (k >= t && cross(H[k-2], H[k-1], P[i]) <= 0) 
		{		
			k--;
		}
        H[k++] = P[i];
    }
}
